#!/bin/sh
# @author: Philippe Coval <https://wiki.tizen.org/wiki/User:Pcoval>
set -e
set -x

die_()
{
    echo "error: $@"
    exit 1
}

setup_debian_()
{
    which apt-get \
        || die_ "TODO: port to non debian systen"

    which sudo \
        || die_ "TODO: install sudo"

    sudo apt-get remove obs-build depanneur gbs
    
    sudo apt-get install -f

    sudo apt-get install \
        curl \
        file \
        git \
        libxml2-utils \
        make \
        realpath \
        rpm \
        rpm2cpio \
        sudo \
        time \
        unp \
        wget \
        zip \
        || die_ "TODO: missing tools"


    .  /etc/os-release
    NAME=$(echo "$NAME" | sed -e 's|\([^ ]*\) .*|\1|g')
    url="http://download.tizen.org/tools/latest-release/${NAME}_${VERSION_ID}/"
    file="/etc/apt/sources.list.d/org_tizen.list"
    [ -r "$file" ] || cat<<EOF | sudo tee "$file"
deb $url /
deb-src $url /
EOF
    sudo apt-get update
    
    sudo apt-get install \
        bmap-tools \
        gbs \
        lthor \
        mic \
        || die_ "TODO: missing tools"
}


setup_fedora_()
{
    # TODO: use: dnf, align to debian packages
    sudo yum install \
        curl \
        file \
        git \
        make \
        realpath \
        wget \
        zip \
        || die_ "TODO: missing tools"

    . /etc/os/release
    #ie:  NAME=Fedora # ID=fedora # VERSION_ID=20
    url="http://download.tizen.org/tools/latest-release/${NAME}_${VERSION_ID}/tools.repo"
    sudo yum-config-manager --add-repo "${url}"
    sudo yum update
    sudo yum install gbs sdb
}


setup_()
{
    cat<<EOF
# WARNING: This script may ask root permissions to install package
# Let it go, or press control+C now and review this script manually
# less $0
# and then run it:
# $0 setup

EOF

    env=/etc/os-release
    [ -r "${env}" ] || die_ "TODO: not LSB system"
    
    if [ -f /etc/debian_version ]; then
        setup_debian_
    elif [ -f /etc/fedora_release ]; then
        setup_fedora_
    else
        die_ "TODO: port for $env"
    fi

    which dirname \
        && which realpath \
        && which git \
        && which gbs \
        && which make \
        && return 0 \
        #eol

    return 1
}


main_()
{
    setup_ "$@"
}


main_ "$@"
